var api = require("../config/api.js");

// var QQMapWX = require("../lib/qqmap/qqmap-wx-jssdk.min.js");

var qqmapsdk;
const app = getApp();

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}
/**
 * 封封微信的的request
 */


function request(url, data = {}, method = "GET") {
  return new Promise(function (resolve, reject) {
    uni.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': 'application/json',
        'X-Access-Token': uni.getStorageSync('uniIdToken')
      },
      success: function (res) {
        // console.log("success>>"+JSON.stringify(res));
		this.loaded = true;
        if (res.data.errno == 401 || res.data.errno == 401) {
			console.log("gologin")
          // return loginByWeixin();
          return gologin();
        } else {
          resolve(res.data);
        }
      },
      fail: function (err) {
        reject(err);
        console.log("failed");
      }
    });
  });
}

function uploadFile(url, data = {}, method = "POST") {
  return new Promise(function (resolve, reject) {
	  uni.uploadFile({
	    filePath: data,
	    name: 'file',
	    url: api.Upload,
	    success: function (res) {
	      // console.log(JSON.stringify(res))
		  // console.log("success>>"+JSON.stringify(res));
		  this.loaded = true;
		  if (res.data.errno == 401 || res.data.errno == 401) {
		  	// console.log("gologin")
		    // return loginByWeixin();
		    return gologin();
		  } else {
		    resolve(res.data);
		  }
	    },
		  fail: function (err) {
			reject(err);
			console.log("failed");
		  }
	  });
	  
  //   uni.uploadFile({
  //     url: url,
  //     data: data,
  //     method: method,
  //     header:{"Content-Type": "multipart/form-data"},
  //     success: function (res) {
  //       // console.log("success>>"+JSON.stringify(res));
		// this.loaded = true;
  //       if (res.data.errno == 401 || res.errno == 401) {
		// 	console.log("gologin")
  //         // return loginByWeixin();
  //         return gologin();
  //       } else {
  //         resolve(res.data);
  //       }
  //     },
  //     fail: function (err) {
  //       reject(err);
  //       console.log("failed");
  //     }
  //   });
  });
}

function get(url, data = {}) {
  return request(url, data, 'GET');
}

function post(url, data = {}) {
  return request(url, data, 'POST');
}
function upload(url, data = {}) {
  return uploadFile(url, data, 'POST');
}
/**
 * 检查微信会话是否过期
 */


function checkSession() {
  return new Promise(function (resolve, reject) {
    uni.checkSession({
      success: function () {
        resolve(true);
      },
      fail: function () {
        reject(false);
      }
    });
  });
}
/**
 * 系统登录
 */

function gologin(){
	console.log("==gologin==");
	uni.navigateTo({
		url: '/pagesA/auth/login'
	})
	return false;
}
function loginByWeixin() {
  let code = null;
  return new Promise(function (resolve, reject) {
    return login().then(res => {
      code = res;
      return getUserInfo();
    }).then(userInfo => {
      //登录远程服务器
      var invitationCode = uni.getStorageSync("invitationCode");
      // console.log("invitationCode:" + JSON.stringify(invitationCode));
      request(api.AuthLoginByWeixin, {
        code: code,
        userInfo: userInfo,
        invitationCode: invitationCode
      }, 'POST').then(res => {
        // console.log("loginInfo:" + JSON.stringify(res));
        if (res.errno == 0) {
          //存储用户信息
          uni.setStorageSync('userInfo', res.data.userInfo);
          uni.setStorageSync('token', res.data.token);
          uni.setStorageSync('brandId', res.data.brandId);
          app.globalData.userInfo = res.data.userInfo;
          app.globalData.token = res.data.token;
          app.globalData.brandId = res.data.brandId; // console.log("loginByWeixin res:" + JSON.stringify(res));

          getSetting();
          resolve(res);
        } else {
          uni.showToast({
            image: "/static/static/images/icon_error.png",
            title: '登录失败'
          });
          reject(res);
        }
      }).catch(err => {
        reject(err);
      });
    }).catch(err => {
      reject(err);
    });
  });
}
/**
 * 调用微信登录
 */


function login() {
  return new Promise(function (resolve, reject) {
    // console.log("wx login start!");
    uni.login({
		provider:'weixin',
      success: function (res) {
        // console.log("wx login res:"+JSON.stringify(res));
        if (res.code) {
          resolve(res.code);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function isLogin() {
	//#ifndef MP-WEIXIN
		return true
	//#endif
  if (uni.getStorageSync('token')) {
    return true;
  }

  return false;
}

function getUserInfo() {
  return new Promise(function (resolve, reject) {
    uni.getUserInfo({
      withCredentials: true,
	  provider:'weixin',
      success: function (res) {
        // console.log("==getUserInfo=="+JSON.stringify(res))
        if (res.errMsg == 'getUserInfo:ok') {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function (err) {
        reject(err);
      }
    });
  });
}

function redirect(url) {
  //判断页面是否需要登录
  if (false) {
    uni.redirectTo({
      url: '/pagesA/auth/login/login'
    });
    return false;
  } else {
    uni.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  uni.showToast({
    title: msg,
    image: "/static/static/images/icon_error.png"
  });
}

function getSetting() {
  //获取用户的当前设置
  //#ifdef MP-WEIXIN
  return new Promise(function (resolve, reject) {
    const _this = this;

    uni.getSetting({
      success: res => {
        // console.log('getSetting=='+JSON.stringify(res))
        // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          //未授权
          uni.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                uni.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                });
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                uni.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.userLocation"] == true) {
                      uni.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      }); //再次授权，调用wx.getLocation的API

                      getLocation().then(function (res) {
                        resolve(res);
                      });
                    } else {
                      uni.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      });
                    }
                  }
                });
              }
            }
          });
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //用户首次进入页面,调用wx.getLocation的API
          getLocation().then(function (res) {
            resolve(res);
          });
        } else {
          // console.log('授权成功')
          getLocation().then(function (res) {
            resolve(res);
          });
        }
      }
    });
  });
  //#endif
  //#ifndef MP-WEIXIN
  return new Promise(function (resolve, reject) {
  	  resolve("");
  })
  //#endif
}

// function getLocation() {
//   return new Promise(function (resolve) {
//     uni.getLocation({
//       type: "wgs84",
//       success: function (res) {
//         console.log("==getLocation==" + JSON.stringify(res));
//         qqmapsdk = new QQMapWX({
//           key: 'FVGBZ-6AP3X-3YA45-7FCUG-XW2JK-OHBHG' //这里自己的key秘钥进行填充

//         });
//         qqmapsdk.reverseGeocoder({
//           location: {
//             latitude: res.latitude,
//             longitude: res.longitude
//           },
//           success: function (res) {
//             let province = res.result.ad_info.province;
//             let city = res.result.ad_info.city; // console.log("location===" + JSON.stringify(res.result));
//             // console.log("====" + encodeURIComponent(city));

//             uni.setStorageSync("location", res.result.location);
//             resolve(city);
//           },
//           fail: function (res) {
//             console.log(res);
//           },
//           complete: function (res) {}
//         }); // resolve(res)
//       },
//       fail: function () {}
//     });
//   });
// }

module.exports = {
  formatTime,
  request,
  get,
  post,
  redirect,
  showErrorToast,
  checkSession,
  login,
  getUserInfo,
  // getLocation,
  getSetting,
  loginByWeixin,
  isLogin,
  gologin,
  upload,
};